package cn.progen.sqlbuilder;

import java.util.ArrayList;
import java.util.List;

public class SqlBuilder {
	private String[] fields;
	private IWhere where;
	private List<String> table=new ArrayList<>();
	private String alias;
	private String type;
	
	
	public String getAlias() {
		return alias;
	}
	public SqlBuilder setAlias(String alias) {
		this.alias = alias;
		return this;
	}
	public String getTable() {
		StringBuilder sb=new StringBuilder();
		for (int i = 0; i < table.size(); i++) {
			if(i>0){
				sb.append(",");
			}
			sb.append(table.get(i));
		}
		return sb.toString();
	}
	public SqlBuilder setTable(String table) {
		this.table.add(table) ;
		return this;
	}
	public String getFields() {
		//return fields;
		StringBuilder sb=new StringBuilder();
		for (int i = 0; i < fields.length; i++) {
			if(i>0){
				sb.append(",");
			}
			sb.append(fields[i]);
		}
		return sb.toString();
	}
	
	
	public SqlBuilder setFields(String... fields) {
		this.fields = fields;
		return this;
	}
	public IWhere getWhere() {
		return where;
	}
	public SqlBuilder setWhere(IWhere where) {
		this.where = where;
		return this;
	}
	public SqlBuilder select(){
		this.type="select";
		return this;
	}
	public String getSql(){
//		if(this.type.equals("select")){
//			return getSelectSql();
//		}
		return getSelectSql();		
	}
	
	
	
	public String getSelectSql(){
		StringBuilder sb=new StringBuilder();
		sb.append(this.type).append(" ").append(this.getFields()).append(" from ").append(this.getTable()).append(" ");
		if(this.where!=null&&this.where.getSql().length()>=1){
			sb.append(" where ").append(this.where.getSql());
		}			
		return sb.toString();		
	};
	
	public SqlBuilder join(SqlBuilder sqlBuilder){	
		setTable(" ( "+sqlBuilder.getSql()+" ) as "+sqlBuilder.getAlias());
		return this;		
	}
	public SqlBuilder() {
		super();
		this.where=new WhereBuilder();
	}
	
	
}
